package com.iflytek.aisol.audit.iflytek.strategy.manage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.iflytek.aisol.audit.iflytek.strategy.manage.config.CustomException;
import com.iflytek.aisol.audit.iflytek.strategy.manage.constant.TableColumnInitConstant;
import com.iflytek.aisol.audit.iflytek.strategy.manage.dto.DisLimitConfigDTO;
import com.iflytek.aisol.audit.iflytek.strategy.manage.entity.ChannelConfig;
import com.iflytek.aisol.audit.iflytek.strategy.manage.entity.DisLimitConfig;
import com.iflytek.aisol.audit.iflytek.strategy.manage.mapper.ChannelConfigMapper;
import com.iflytek.aisol.audit.iflytek.strategy.manage.mapper.DisLimitConfigMapper;
import com.iflytek.aisol.audit.iflytek.strategy.manage.service.DisLimitConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;

/**
 * @author zxwu17
 */
@Service
public class DisLimitConfigServiceImpl implements DisLimitConfigService {
    @Autowired
    private DisLimitConfigMapper disLimitConfigMapper;

    @Autowired
    private ChannelConfigMapper channelConfigMapper;
    /**
     * 新增限流配置
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void add(DisLimitConfigDTO disLimitConfigDTO) {
        // 拿channelConfigId去数据库表查，如果查到有记录，则执行，查不到报错
        // 获取channelId
        Long channelConfigId = disLimitConfigDTO.getChannelConfigId();
        Optional<ChannelConfig> channelConfig = channelConfigMapper.findById(channelConfigId);
        if(!channelConfig.isPresent()){
            throw new CustomException(TableColumnInitConstant.ERROR,"您配置的channelConfigId在数据库不存在");
        }else{
            DisLimitConfig disLimitConfig = new DisLimitConfig();
            BeanUtil.copyProperties(disLimitConfigDTO,disLimitConfig);
            disLimitConfigMapper.save(disLimitConfig);
        }
    }
    /**
     * 修改限流配置
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void update(Long id, DisLimitConfigDTO disLimitConfigDTO) {
        // 先去数据库查有没有该条记录
        Optional<DisLimitConfig> disLimit = disLimitConfigMapper.findById(id);
        // 如果不存在报错
        if(!disLimit.isPresent()){
            throw new CustomException(TableColumnInitConstant.ERROR,"您配置的disLimitConfigId在数据库不存在");
        }else{
            // 存在可以修改
            DisLimitConfig disLimitConfig = disLimit.get();
            disLimitConfig.setChannelConfigId(disLimitConfigDTO.getChannelConfigId());
            disLimitConfig.setQps(disLimitConfigDTO.getQps());
            disLimitConfig.setAppId(disLimitConfigDTO.getAppId());
            disLimitConfigMapper.save(disLimitConfig);
        }

    }
    /**
     * 删除限流配置
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void delete(Long id) {
        disLimitConfigMapper.deleteById(id);
    }

}
